package com.itzyf.pokemondata.activity.gallery

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.view.Menu
import android.view.MenuItem
import android.webkit.WebSettings
import android.webkit.WebView
import com.itzyf.pokemondata.R
import com.qmuiteam.qmui.widget.webview.QMUIWebViewClient
import com.tydic.baselibrary.activity.BaseActivity
import com.tydic.baselibrary.utils.AppUtils
import kotlinx.android.synthetic.main.activity_webview.*


class WebViewActivity : BaseActivity() {
    override fun handlerActivity() {
        setTitle(intent.getStringExtra("title"))
        showProgressDialog()
        webView.loadUrl(intent.getStringExtra("httpUrl"))
        webView.settings.displayZoomControls = false
        webView.settings.blockNetworkImage = false
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        webView.webViewClient = LoadingWebViewClient()
    }

    override fun getContentViewId() = R.layout.activity_webview

    override fun getToolbarTitle() = ""


    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.browser, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        if (item?.itemId == R.id.action_open_browser) {
            val uri = Uri.parse(intent.getStringExtra("httpUrl"))
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    inner class LoadingWebViewClient : QMUIWebViewClient(false, false) {

        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
            if (this@WebViewActivity.isDestroyed || this@WebViewActivity.isFinishing) {
                return
            }

            super.onPageStarted(view, url, favicon)
        }

        override fun onPageFinished(view: WebView?, url: String?) {
            if (this@WebViewActivity.isDestroyed || this@WebViewActivity.isFinishing) {
                return
            }
            dismissProgressDialog()
            super.onPageFinished(view, url)
        }

        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
            url.let {
                return if (it!!.startsWith("http://") || it.startsWith("https://")) {
                    super.shouldOverrideUrlLoading(view, url)
                } else {
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    if (intent.resolveActivity(packageManager) != null) {
                        startActivity(intent)
                    }
                    true
                }
            }
        }
    }


}